"""
Notepad contains several panelbars, for compact viewing
Written By: Daniel Ortiz
"""
import wx
import wx.lib.flatnotebook as fnb
from panelbar import MailPanelBar
from database.mapclass import *

class MailFlatNotebook(fnb.FlatNotebook):
    def __init__(self, parent):
        self.parent = parent
        fnb.FlatNotebook.__init__(self, parent)
        self.Variables()
        self.InitializePage()
        self.BindEvents()
        self.BindToHandler()
        
    def Variables(self):
        """Contains the class wide variables"""
        self.data = []    
        self.mailbox = []
        self.length = 15
    
    def InitializePage(self):
        """Initialize page merely calls NewPage with the relevant panel bar"""
        self.NewPage()
        
    def NewPage(self, partial = False):
        """Insert a new page at the relevant position"""
        bar = MailPanelBar(self, text = partial)
        self.AddPage(bar, "")
        
    def BeginSash(self):
        """Iterate over all of the panel bars and call the BeginSash function"""
        for p in range(self.GetPageCount()):
            page = self.GetPage(p)
            page.BeginSash()
            
    def EndSash(self):
        """Iterate over all of the panel bar and call the EndSash function"""
        for p in range(self.GetPageCount()):
            page = self.GetPage(p)
            page.EndSash()
            
    def BindEvents(self):
        """Bind the relevant events of the flat notebook"""
        self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnClosingPage)
        self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnChangingPage)
        
    def OnClosingPage(self, event):
        """Keeps the last page from being deleted"""
        index = self.GetIndex()
        if self.GetPageCount() <= 1:
            page = self.GetPage(0)
            page.Clear()
            event.Veto()
            if self.data:
                self.data.remove(self.data[index])
                self.mailbox.remove(self.mailbox[index])
        else:
            self.data.remove(self.data[index])
            self.mailbox.remove(self.mailbox[index])
        self.AdvanceSelection(False)
    
    def OnChangingPage(self, event):
        """Upon changing the page, checks the editor and correspondingly changes the format menu"""
        p = self.GetTopLevelParent()
        page = self.GetCurrentPage()
        p.ChangeFormatMenu(page.is_text)    
        
    def BindToHandler(self):
        """Bind the notebook to the mailbox handler"""
        d = self.GetTopLevelParent().database_handler
        d.BindMailNotebook(self)
        
    def NewMail(self, mail, attachments, mailbox, partial = False):
        """Visualize a new piece of mail"""
        if not partial:
            for k, d in enumerate(self.data):
                if d == mail:
                    self.SetPage(k)
                    return
        if not self.data:
            index = 0
            page = self.GetPage(0)
        else:
            self.NewPage(partial = partial)
            index = self.GetPageCount() - 1
            page = self.GetPage(index)
        if mail.subject:
            self.SetPageText(index, mail.subject[:self.length])
        page.Display(mail, attachments)
        self.data.append(mail)
        self.mailbox.append(mailbox)
        
    def ClearCurrentName(self):
        """Clear the current page's title"""
        self.SetPageText(self.GetIndex(), '')
        
    def GetIndex(self):
        """Get the current attributes of the frame"""
        return self.GetPageIndex(self.GetCurrentPage())
    
    def SetPage(self, k):
        """Set the current page to kth page"""
        index = self.GetIndex()
        dir = k > index
        for t in range(abs(k - index)):
            self.AdvanceSelection(dir)
            
    def NewIncompleteMail(self, **kw):
        """Create a new page with partial state information"""
        m = create_incomplete_mail(**kw)
        self.NewMail(m, [], kw['mailbox'], partial = True)
        page = self.GetCurrentPage()
        page.SetDraft(True)
        
    def GetCurrentMailData(self):
        """Get the data from the page"""
        return self.GetCurrentPage().GetMailData()
    
    def GetCurrentHTML(self):
        browser = self.GetCurrentPage().mail_browser
        return browser.AsHTML()
    
    def GetCurrentMail(self):
        """Returns the current page's data"""
        index = self.GetIndex()
        return self.data[index], self.mailbox[index]
    
    def IsDraft(self):
        """Returns the a list of mail subjects of the mail that is currently a draft"""
        ret = []
        for p in range(self.GetPageCount()):
            page = self.GetPage(p)
            if page.IsDraft():
                data = page.GetMalboxData()
                ret.append(data["Header"]["Subject"])
        return ret
    
    def DeletePanel(self, mail):
        """Delete the page with the current mail"""
        try:
            index = self.data.index(mail)
            self.DeletePage(index)
        except Exception, e:
            pass
            
    def AddEmailFromAddressBook(self, text, data):
        """Add email from the address book to the active header panel"""
        page = self.GetCurrentPage()
        page.AddressBookHeader(text, data)        
    
    def NewAttachment(self):
        """Find the current page and add an attachment"""
        page = self.GetCurrentPage()
        page.NewAttach()

    def SaveAttachments(self):
        """Save the current attachments of the email"""
        page = self.GetCurrentPage()
        page.SaveAttachments()